<?php

namespace app\api\controller;

use app\api\model\QuesSubjectRecord;
use app\api\model\QuesSubjectExamItem;
use app\api\model\QuesSubject;
use app\common\controller\Api;


/**
 * 首页接口.
 */
class Question extends Api
{
    protected $noNeedLogin = ['cate'];
    protected $noNeedRight = ['*'];


    /**
     * 测评分类
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cate()
    {
        $cateModel = new \app\api\model\QuesCate();
        $subjectRecordModel = new \app\api\model\QuesSubjectRecord();
        $list = $cateModel->field('id,name,type,flag')->order('weigh desc')->where('status', 'normal')->select()->toArray();
        $_list = [];
        if ($this->auth->id) {
            $count = $subjectRecordModel->where('counselor_id', $this->auth->id)->count();
            $count && $_list[] = [
                'id' => 99999,
                'name' => '我的常用'
            ];
        }
        foreach ($list as $vv) {
            $_list[] = [
                'id' => $vv['id'],
                'name' => $vv['name']
            ];
        }
        $this->success('请求成功', $_list);
    }


    /**
     * 题目列表
     * @return void
     */
    public function index()
    {

        $cate_id = $this->request->get('cate_id');
        $keywords = $this->request->get('keywords');
        //如果为我的常用
        if ($cate_id == 99999) {
            $subject_id = (new \app\api\model\QuesSubjectRecord())->group('subject_id')->where('counselor_id', $this->auth->id)->column('subject_id');
            $where['subject_ids'] = $subject_id ? $subject_id : [-1];

        } else {
            $where['category_id'] = $cate_id;
        }
        $model = new QuesSubject();
        $where['keywords'] = $keywords;
        $list = $model->getList($where, 12, 'id,name,source', 'weigh asc');
        foreach ($list['data'] as &$vv) {
            $vv['num'] = (new \app\api\model\QuesSubjectRecord())->where('subject_id', $vv['id'])->where('status', 2)->count();
        }
        $this->success('请求成功', $list);

    }

    public function detail()
    {
        $id = $this->request->get('id');
        $info = (new QuesSubject())->where('id', $id)->find();
        $this->success('请求成功', $info);
    }


    /**
     * 题库题目列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function subject_exam()
    {
        $subject_id = $this->request->get('subject_id');
        $list = (new \app\api\model\QuesSubjectExam())->where('subject_id', $subject_id)->order('weigh asc')->select()->toArray();
        $info = (new QuesSubject())->where('id', $subject_id)->find();
        $SubjectExamItemModel = new QuesSubjectExamItem();
        foreach ($list as &$vv) {
            $vv['item'] = $SubjectExamItemModel->where('subject_exam_id', $vv['id'])->order('weigh asc')->select()->toArray();
            $vv['type'] = $info['stype'];
        }
        $this->success('成功', $list);
    }


    /**
     * 查看报告
     * @return void
     */
    public function report()
    {
        $record_id = $this->request->get('record_id');
        $sublectRecordModel = new QuesSubjectRecord();
        $info = $sublectRecordModel->where('id', $record_id)->with([
            'subject' => function ($query) {
                $query->field('id,name,subject_cate_id');
            },
            'userinfo' => function ($query) {
                $query->field('id,nickname,prevtime,logintime,jointime,mobile');
            },
        ])->field('id,examtime,counselor_id,result,subject_id,user_id,score,report')->find();
        if (empty($info)) {
            $this->error('信息异常');
        }
        $info['qrcode'] = config('site.gongzhonghao');
        $info['link'] = config('site.gongzhonghao_link');

        //1 SCL
        //2	多维度
        //3	单维度
        //4	MBTI
        //5	ORS / SRS

//        switch ($info['subject']['subject_cate_id']) {
//            case '1':
//                $report = [
//                    'all' => [
//                        ['title' => '总分', 'val' => rand(100, 999), 'content' => '有比较严重的心理问题，需医学上的详细检查', 'desc' => '总体得分，能反映病情严重程度。', 'level' => 1],
//                        ['title' => '总均分', 'val' => rand(1, 10),  'content' => '是指总的来者，被试的自我症状评价介于“没有"到“严重”的哪一个水平。', 'desc' => '是指总的来者，被试的自我症状评价介于“没有"到“严
//重”的哪一个水平。', 'level' => 2],
//                        ['title' => '阳性项目数', 'val' => rand(1, 10), 'content' => '阳性因子数较多，超出正常范国', 'desc' => '表示被试在多少项目中感到“有症状”', 'level' => 2],
//                    ],
//                    'factor' => ['desc' => 'SCL-90包括10个因子，每一个因子反映出个体某方面的症状情况，通过因子分可了解症状分布特点。当个体在某一因子的均分大于2时，即超过正常均分，则个体在该方面就很有可能有心理健康方面的问题。', 'item' => [
//                        ['title' => '抑郁', 'score' => rand(10, 40), 'avg_score' => rand(10, 40) / 10, 'max'=>10,'content' => '抑郁程度较强，生活缺乏足够的兴趣，缺乏运动活力，极端情况下，可能会有想死亡的思想和自杀的观念。', 'desc' => '该分星表的得分在0-52分之间。得分越高，抑郁程度越明显，得分越低，抑郁程度越不明显。
//因子介绍:苦闷的情感与心境为代表性症状，还以生话兴迎的减退，动力缺乏，活力丧失等为特征。还表现出失望、悲观以与抑和相联系的认知和躯体方面的感受，另外，还包括有上元亡的思想和自杀观念。','intro'=>'因子介绍'],
//
//                        ['title' => '敌对', 'score' => rand(10, 40), 'avg_score' => rand(10, 40) / 10,'max'=>10, 'content' => '易表现出敌对的思想、情恶和行为。', 'desc' => '该分量表的得分在0-24分之间。得分越高，个体越客易敌对，好争论，脾气难以控制。得分越低，个体的脾气越温和。待人友好，不喜欢争论、无破坏行为。因子介绍:主要从三方面来反映敌对的表现:思想、感情及行为。其项目包括厌烦的感觉，捧物，争论直到不可控制的胂气县发等各方面。','intro'=>'因子介绍'],
//                    ]],
//                    'report_desc' => '《SCL-90心理健康症状自评量表》包含了广泛的精神病症状学内容，如思维、情感、人际关系和生活习惯等。
//该量表从9个方面，以身心症状表现的角度考查了受测者的心理健康水平，如果在某些症状上的得分越高，感觉到某些症状的频度和强度都比较严重，就应该注意受测者在这个方面的问题。
//由于自评量表是测量受测者在一段时间内感觉到的症状的严重与否，所以在量表分数的解释上应该慎重，并不是得分高就一定说明出现了很严重的心理问题，某些分量表上的得分较高有可能只是由于受测者当时遇到了一些难题如失恋、面临考试、生病等，因此还应该对得分高的原因作进一步的了解。
//如果受测者在多个维度上自觉这些症状较为严重时，应该加强心理健康的教育，严重时应该到比较权威的心理咨询和治疗机构进行进一步的检查和诊断。',
//
//                ];
//
//                break;
//            case '3':
//                $report = [
//                    'score' => $info['score'],
//                    'report_title' => '轻度抑郁症',
//                    'report_content' => '测试结果显示出，你目前可能有轻微的情绪波动或轻微的焦虑情绪，比如偶尔会有莫名的紧张，难以放松，对未来的担忧等，这些尚在你可以应付的范里
//                                        内.量表只起到初步判断，如果判断自己是不是抑郁，一定要到专业精神科，医生通过全面精神状态检查判断是不是抑郁症。',
//                    'report_desc' => '参考标准:
//                                    ·0-5分属于健康程度
//                                    10-15分属于轻度抑郁的症状
//                                    >15分称为有抑郁的症状
//                                    >25分称为严重或重度的抑郁症状'
//                ];
//                break;
//            case '5':
//                $report = [
//                    'score' => [['title' => '身心健康', 'score' => 35, 'content' => '身心健康:35','avg_score' => rand(10, 40) / 10,'max'=>10], ['title' => '人际关系', 'score' => 10, 'content' => '身心健康:35','avg_score' => rand(10, 40) / 10,'max'=>10], ['title' => '生活社交', 'score' => 45, 'content' => '身心健康:35','avg_score' => rand(10, 40) / 10,'max'=>10], ['title' => '整体情况', 'score' => 45, 'content' => '身心健康:35','avg_score' => rand(10, 40) / 10,'max'=>10]],
//                    'report_title' => '',
//                    'report_content' => '',
//                    'report_desc' => ''
//                ];
//
//                break;
//
//        }

        $info['examtime'] = date('Y-m-d H:i:s', $info['examtime']);
        $info['report'] = json_decode($info['report'], true);

        $report_url = '';
        switch ($info['subject']['subject_cate_id']) {
            case '1':
                $url = env('TEST.BASEURL') . "/wap/#/pages/onlineTest/lookResultInfoDetail?record_id=" . $record_id;
                break;
            case '3':
                $url = env('TEST.BASEURL') . "/wap/#/pages/onlineTest/lookResultInfo?record_id=" . $record_id;
                break;
            case '5':
                $url = env('TEST.BASEURL') . "/wap/#/pages/onlineTest/lookResultInfoother?record_id=" . $record_id;
                break;
            default:
                $this->error('报告异常');
        }
        $info['report_url'] = $report_url;

        $this->success('成功', $info);

    }

    /**
     * 题库测评记录
     * @return void
     */
    public function exam_record()
    {

        try {

            $record_id = $this->request->get('record_id');
            $sublectRecordModel = new QuesSubjectRecord();
            $info = $sublectRecordModel->where('id', $record_id)->field('id,examtime,result,subject_id')->find();
            $result = json_decode($info['result'], true);
//        dump($result);die;
            $exam_ids = array_column($result, 'questionId');
            $list = (new \app\api\model\QuesSubjectExam())
                ->where('subject_id', $info['subject_id'])
                ->where('id', 'in', $exam_ids)
                ->order('weigh asc')->select()->toArray();

            if (empty($info)) {
                $this->error('系统异常');
            }
            $subjectinfo = (new QuesSubject())->where('id', $info['subject_id'])->find();
            if (empty($subjectinfo)) {
                $this->error('系统异常');
            }


            $checkoptionids = [];
            foreach ($result as $vv) {
                if ($vv['questionType'] == 1) {
                    $checkoptionids[$vv['questionId']][$vv['checkOptionId']] = ['checkOptionId' => $vv['checkOptionId'], 'questionType' => $vv['questionType']];
                }

                if ($vv['questionType'] == 2) {
                    foreach ($vv['checkOptionlist'] as $v2) {
                        $checkoptionids[$vv['questionId']][$v2['silderOptionId']] = ['checkOptionId' => $v2['silderOptionId'], 'questionType' => $vv['questionType'], 'silderOptionValue' => $v2['silderOptionValue']];
                    }
                }

            }

            $SubjectExamItemModel = new QuesSubjectExamItem();
            foreach ($list as &$vv) {
                $item_list = $SubjectExamItemModel->where('subject_exam_id', $vv['id'])->order('weigh asc')->select()->toArray();

                foreach ($item_list as &$v3) {
                    $v3['selected'] = [
                        'checkOptionId' => 0,
                        'questionType' => $vv['type'],
                    ];
                    if (isset($checkoptionids[$vv['id']][$v3['id']])) {
                        $v3['selected'] = $checkoptionids[$vv['id']][$v3['id']];
                    }
                    $vv['type'] = $subjectinfo['stype'];
                }
                $vv['item'] = $item_list;
            }
            $this->success('成功', $list);

        } catch (\Exception $e) {
            $this->error('系统异常，请联系客服');
        }
    }

    /**
     * 来访列表
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userlist()
    {
        $sublectRecordModel = new QuesSubjectRecord();
        $userlist = $sublectRecordModel->where('status', 2)->where('counselor_id', $this->auth->id)->with([
            'quser' => function ($query) {
                $query->field('id,nickname,mobile');
            },
        ])->group('user_id')->field('user_id')->select()->toArray();
        $_list = [];
        foreach ($userlist as $vv) {
            $_list[] = [
                'user_id' => $vv['user_id'],
                'name' => $vv['quser']['nickname'],
            ];
        }
        $this->success('成功', $_list);

    }


    /**
     * 用户测评列表
     * @return void
     */
    public function userRecordList()
    {

        try {

            $user_id = $this->request->get('user_id');
            $subject_id = $this->request->get('subject_id');
            $size = $this->request->get('size', 12);
            $keywords = $this->request->get('keywords');

            if ($user_id <= 0) {
                $this->error('参数错误', ['msg' => 'user_id 必填']);
            }
            $sublectRecordModel = new QuesSubjectRecord();
            $subject = $sublectRecordModel->where('status', 2)->where('counselor_id', $this->auth->id)->where('user_id', $user_id)
                ->where(function ($query) use ($keywords) {
                    if ($keywords) {
                        $query->where('username|usermobile', "like", "%" . $keywords . "%");
                    }
                })
                ->with([
                    'subject' => function ($query) {
                        $query->field('id,name');
                    },
                ])
                ->group('subject_id')
                ->field('subject_id,count(id) as num')->select()->toArray();
            $total = [];

            foreach ($subject as $vv) {
                $total[] = [
                    'subject_id' => $vv['subject_id'],
                    'num' => $vv['num'],
                    'name' => isset($vv['subject']['name']) ? $vv['subject']['name'] : '未知',
                ];
            }
            if (!$subject_id) {
                $subject_id = isset($total[0]['subject_id'])?$total[0]['subject_id']:0;
            }
            $list = $sublectRecordModel->where(function ($query) use ($subject_id, $user_id, $keywords) {
                if ($subject_id > 0) {
                    $query->where('subject_id', $subject_id);
                }
                if ($user_id > 0) {
                    $query->where('user_id', $user_id);
                }

                if ($keywords) {
                    $query->where('username|usermobile', "like", "%" . $keywords . "%");
                }
            })
                ->with(['subject' => function ($query) {
                    $query->field('id,name,subject_cate_id');
                }, 'quser' => function ($query) {
                    $query->field('id,nickname,mobile');
                }])
                ->where('counselor_id', $this->auth->id)
                ->where('status', 2)
                ->field('id,user_id,subject_id,score,endtime')
                ->order('id desc')
                ->paginate($size);
            $list = $list->toArray();

            foreach ($list['data'] as &$vv) {
                $vv['endtime'] = date('Y-m-d H:i:s', $vv['endtime']);
            }
            $this->success('成功', ['list' => $list, 'total' => $total]);

        } catch (\Exception $e) {
            $this->error('系统异常,请联系客服!');
        }
    }


    /** 按状态查询用户测评列表
     * @return void
     */
    public function userRecordListByStatus()
    {

        $page = $this->request->get('page');
        $size = $this->request->get('size');
        $keywords = $this->request->get('keywords');
        $status = $this->request->get('status');
        $sublectRecordModel = new QuesSubjectRecord();
        $list = $sublectRecordModel->where(function ($query) use ($status, $keywords) {
            if ($status > 0) {
                $query->where('status', $status);
            }else{
                $query->where('status','in', [1,2,3]);
            }
            if ($keywords) {
                $query->where('usermobile|username|subject_name', 'like', "%{$keywords}%");
            }
        })
            ->with(['subject' => function ($query) {
                $query->field('id,name,subject_cate_id');
            }, 'quser' => function ($query) {
                $query->field('id,nickname,mobile');
            }])
            ->where('counselor_id', $this->auth->id)
//            ->where('status', 2)
            ->field('id,user_id,subject_id,score,endtime,starttime,username,usermobile,status')
            ->order('id desc')
            ->paginate($size);
        $list = $list->toArray();
        foreach ($list['data'] as &$vv) {
            $vv['endtime'] = $vv['endtime']? date('Y-m-d H:i:s', $vv['endtime']):'--';
            $vv['starttime'] = date('Y-m-d H:i:s', $vv['starttime']);
        }
        $this->success('成功', $list);
    }

    /**
     * 撤销
     * @return void
     */
    public function revoke()
    {
        $record_id = $this->request->get('record_id');

        if ($record_id <= 0) {
            $this->error('参数异常', ['msg' => 'record_id 异常']);
        }
        $sublectRecordModel = new QuesSubjectRecord();
        $info = $sublectRecordModel->where('id', $record_id)->where('counselor_id', $this->auth->id)->find();
        if (empty($info) || $info['status'] != 1) {
            $this->error('信息异常', ['msg' => '未找到记录或者状态不支持撤销']);
        }
        $result = $sublectRecordModel->where('id', $record_id)->update(['status' => 3]);
        if ($result !== false) {
            $this->success('成功');
        } else {
            $this->error('失败');
        }
    }


    /**
     * 重新发起
     * @return void
     */
    public function restart()
    {

        $record_id = $this->request->get('record_id');

        if ($record_id <= 0) {
            $this->error('参数异常', ['msg' => 'record_id 异常']);
        }
        $sublectRecordModel = new QuesSubjectRecord();
        $info = $sublectRecordModel->where('id', $record_id)->where('counselor_id', $this->auth->id)->with(['subject'])->find();
        if (empty($info)) {
            $this->error('信息异常', ['msg' => '未找到记录']);
        }

        $quesuser = (new \app\api\model\QuesUser())->where('id', $info['user_id'])->find();
        $data = [
            'subject_id' => $info['subject_id'],
            'counselor_id' => $info['counselor_id'],
            'user_id' => $info['user_id'],
            'starttime' => time(),
            'counselor' => $this->auth->nickname,
            'subject_name' => $info['subject']['subject_name'],
            'username' => $quesuser['nickname'],
            'usermobile' => $quesuser['mobile'],
            'status' => 1,
        ];

        $result = $sublectRecordModel->insert($data);
        if ($result !== false) {
            $this->success('成功');
        } else {
            $this->error('失败');
        }
    }

    /**
     * 分享
     * @return void
     */
    public function sendSubject()
    {


        $subject_id = $this->request->get('subject_id');
        $type = $this->request->get('type');
        $record_id = $this->request->get('record_id');


        //如果是获取报告地址
        if ($type == 'report') {
            $report_url = '';
            $sublectRecordModel = new QuesSubjectRecord();
            $info = $sublectRecordModel->where('id', $record_id)->with([
                'subject' => function ($query) {
                    $query->field('id,name,subject_cate_id');
                },
                'userinfo' => function ($query) {
                    $query->field('id,nickname,prevtime,logintime,jointime,mobile');
                },
            ])->field('id,examtime,counselor_id,result,subject_id,user_id,score,report')->find();
            if (empty($info)) {
                $this->error('信息异常');
            }

            switch ($info['subject']['subject_cate_id']) {
                case '1':
                    $url = env('TEST.BASEURL') . "/wap/#/pages/onlineTest/lookResultInfoDetail?record_id=" . $record_id;
                    break;
                case '3':
                    $url = env('TEST.BASEURL') . "/wap/#/pages/onlineTest/lookResultInfo?record_id=" . $record_id;
                    break;
                case '5':
                    $url = env('TEST.BASEURL') . "/wap/#/pages/onlineTest/lookResultInfoother?record_id=" . $record_id;
                    break;
                default:
                    $this->error('报告异常');
            }
            $info['report_url'] = $report_url;
            $this->success('成功', ['url' => $url]);
        }

        $info = (new QuesSubject())->where('id', $subject_id)->find();
        if ($subject_id <= 0 || empty($info)) {
            $this->error('信息异常', ['msg' => '未找到信息']);
        }
        $data = [
            'subject_id' => $subject_id,
            'counselor_id' => $this->auth->id,
            'user_id' => 0,
            'starttime' => time(),
            'counselor' => $this->auth->nickname,
            'subject_name' => $info['subject_name'],
            'status' => 1,
        ];
        $sublectRecordModel = new QuesSubjectRecord();
        $result = $sublectRecordModel->insertGetId($data);
        if ($result !== false) {

            $url = env('TEST.BASEURL') . "/wap/#/pages/onlineTest/BecDepressionInventory?subject_id={$data['subject_id']}&record_id={$result}&counselor_id={$data['counselor_id']}";

            $this->success('成功', ['url' => $url]);
        } else {
            $this->error('失败');
        }

    }

    /**
     * 评分记录
     * @return void
     */
    public function scoreChange()
    {

        $subject_id = $this->request->get('subject_id'); //科目
        $user_id = $this->request->get('user_id');
        $sublectRecordModel = new QuesSubjectRecord();
        $subject = $sublectRecordModel->where('status', 2)->where('counselor_id', $this->auth->id)->where('user_id', $user_id)->with([
            'subject' => function ($query) {
                $query->field('id,name');
            },
        ])
            ->group('subject_id')
            ->field('subject_id,count(id) as num')->select()->toArray();
        $total = [];

        //测评量表汇总
        $num = 0;
        foreach ($subject as $vv) {
            $total[] = [
                'subject_id' => $vv['subject_id'],
                'num' => $vv['num'],
                'name' => isset($vv['subject']['name']) ? $vv['subject']['name'] : '未知',
            ];
            $num += $vv['num'];
        }
        if (!$subject_id) {
            $subject_id = $total[0]['subject_id'];
        }
        $info = (new QuesSubject())->where('id', $subject_id)->find();
        if ($subject_id <= 0 || empty($info)) {
            $this->error('信息异常', ['msg' => '未找到信息']);
        }
        $subjectlist = $sublectRecordModel->where('status', 2)
            ->where('counselor_id', $this->auth->id)
            ->where('user_id', $user_id)
            ->where('subject_id', $subject_id)
            ->with(['subject'])
            ->select()->toArray();
        //规划表格信息
        $table = [];
        $temp = [];
        $max = 0;
        foreach ($subjectlist as $vv) {
            switch ($vv['subject']['subject_cate_id']) {
                case '1':
                    $report = json_decode($vv['report'], true);
                    foreach ($report['all'] as $v2) {
                        $temp[] = [
                            'title' => $v2['title'],
                            'date' => date('y-m-d', $vv['starttime']),
                            'val' => $v2['val'],
                        ];
                        if ($v2['val'] > $max) {
                            $max = $v2['val'];
                        }
                    }
                    $table[] = $temp;
                    break;
                case '3':
                    $table[] = [['title' => '总分', 'date' => date('ymd', $vv['endtime']), 'val' => $vv['score']]];
                    if ($vv['score'] > $max) {
                        $max = $vv['score'];
                    }
                    break;
                case '5':
                    $report = json_decode($vv['report'], true);
                    foreach ($report['score'] as $v2) {
                        $temp[] = [
                            'title' => $v2['title'],
                            'date' => date('y-m-d', $vv['starttime']),
                            'val' => $v2['score'],
                        ];
                        if ($v2['score'] > $max) {
                            $max = $v2['score'];
                        }
                    }
                    $table[] = $temp;
                    break;
            }
        }
            //用户信息
            $uinfo = (new \app\api\model\QuesUser())->where('id', $user_id)->field('id,mobile,nickname')->find();
            $this->success('成功', ['num' => $num, 'total' => $total, 'table' => $table, 'uinfo' => $uinfo, 'max' => $max]);

    }

}
